<?php

namespace app\group\controller\admin\order;

use app\group\model\order\GroupTicket as GroupTicketModel;
use app\shop\model\order\OrderItem as OrderItemModel;
use sheep\controller\Backend;
use think\exception\ValidateException;
use think\facade\Db;
use think\Request;
use app\group\service\goods\GoodsService;
use app\shop\model\order\Order as OrderModel;

/**
 * 核销控制器
 */
class WriteOff extends Backend
{
    public $organ_id;
    public function initialize()
    {
        $this->organ_id = $this->shopId();
        $this->model = new OrderModel;
        $this->itemModel = new OrderItemModel;
        $this->ticketModel = new GroupTicketModel;
    }

    /**
     * 核销张数
     *
     * @return \think\Response
     */
    public function list(Request $request)
    {
        $param = $request->param();
        // 获取子订单信息
        $item_number = $this->itemModel->where(['id' => $param['id']])
            ->whereRaw('(aftersale_status <> 1 or refund_status <> 2) AND (refund_status <> 1 or refund_status <> 2)') //['aftersale_status' => 0, 'refund_status' => 0]
            ->column('id');

        // 获取未核销的也为过期的团购核销码
        $write = $this->ticketModel
            ->field('id, code, order_id, order_item_id')
            ->where('order_item_id', 'in', $item_number)
            ->where('status', '=', 0)
            ->where('validity_time', '>=', time())
            ->select();
        $write_number = $write->count();

        return success('获取成功', ['count' => $write_number, 'list' => $write]);
    }

    // 团购核销
    public function writeOff(Request $request)
    {
        $param = $request->param();
        if (empty($param['id'])) {
            return error('参数有误');
        }
        if (empty($param['write_num']) || $param['write_num'] <= 0) {
            return error('参数有误,请输入核销张数');
        }

        $orderItem = $this->itemModel->where(['id' => $param['id']])->find();
        if ($orderItem->isEmpty()) {
            return error('找不到订单信息');
        }

        $order = $this->model->where(['id' => $orderItem['order_id']])->find();
        if ($order['status'] == OrderModel::STATUS_UNPAID) {
            return error('该订单未支付，无法核销');
        }

        if ($orderItem['aftersale_status'] >= 1  && $orderItem['refund_status'] < 1) {
            return error('该订单已申请售后，无法核销');
        } elseif ($orderItem['refund_status'] >= 1) {
            return error('该订单已申请退款，无法核销');
        }

        // 未使用 未过期的核销码
        $write = $this->ticketModel
            ->field('id, code, status, validity_time, order_id, order_item_id')
            ->where('order_item_id', 'in', $param['id'])
            ->where('status', '=', 0)
            ->where('validity_time', '>=', time())
            ->select();

        // 未使用 已过期的核销码
        $expiredWrite = $this->ticketModel
            ->field('id, code, status, validity_time, order_id, order_item_id')
            ->where('order_item_id', 'in', $param['id'])
            ->where('status', '=', 0)
            ->where('validity_time', '<', time())
            ->select();

        if ($write->isEmpty() && $expiredWrite->isEmpty()) {
            return error('所有核销码已核销');
        }

        $user = $this->auth()->user();

        $cutepetDb             = Db::connect('mysql_cutepet');
        // 未过期的票
        if (!$write->isEmpty()) {
            // 获取核销张数
            $write_count = $write->count();
            $write_num = min($write_count, $param['write_num']);
            // 同步萌宠霸王
            $cutletGroupGoodsData['status'] = 1;
            $cutletGroupGoodsData['use_time'] = time();

            for ($i = 0; $i < $write_num; $i++) {
                GroupTicketModel::update(['status' => 1, 'use_time' => time(), 'write_people' => $user->account, 'write_mobile' => $user->mobile], ['id' => $write[$i]['id']]);
                $cutepetDb->name('group_ticket')->where('code', $write[$i]['code'])->update($cutletGroupGoodsData);
            }

            // 检查是否有剩余未核销的票
            $remainingTickets = $this->ticketModel
                ->where('order_item_id', 'in', $param['id'])
                ->where('status', '=', 0)
                ->count();
            // 如果没有剩余未核销的票，更新订单状态为完成
            if ($remainingTickets == 0) {
                $order_id = $write[0]['order_id'];
                OrderItemModel::update(['dispatch_status' => 2], ['id' => $param['id']]);
                OrderModel::update(['status' => 'completed'],['id' => $order_id]);

                $cutepetDb->name('shop_order_item')->where('id', $param['id'])->update(['dispatch_status' => 2]);
                $cutepetDb->name('shop_order')->where('id', $order_id)->update(['status' => 'completed']);
            }
        }

        // 如果有已过期的票，更新状态
        if (!$expiredWrite->isEmpty()) {
            foreach ($expiredWrite as $expired) {
                GroupTicketModel::update(['status' => -2, 'use_time' => time()], ['id' => $expired['id']]);
                $cutepetDb->name('group_ticket')->where('code', $expired['code'])->update(['status' => -2, 'use_time' => time()]);
//                $cutepetDb->name('shop_order_item')->where('id', $param['id'])->update(['dispatch_status' => 1]);
//                $cutepetDb->name('shop_order')->where('id', $expired['order_id'])->update(['status' => 'closed']);
            }
        }

        return success('核销成功');
    }


}